package com.steam.xbcc.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.steam.xbcc.domain.CourseOrder;
import com.steam.xbcc.dto.KillPreOrderParamDto;
import com.steam.xbcc.enums.GlobalExceptionCode;
import com.steam.xbcc.service.ICourseOrderService;
import com.steam.xbcc.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "course-order-handler-delay-group",
        topic = "course-order-handler-delay-topic",
        selectorExpression = "course-order-handler-delay-tag",
        messageModel = MessageModel.BROADCASTING
)
public class CourseOrderHandlerDelayConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private ICourseOrderService courseOrderService;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void onMessage(MessageExt messageExt) {
        //业务校验
        byte[] body = messageExt.getBody();
        String orderNo = new String(body, StandardCharsets.UTF_8);
        AssertUtil.isNotEmpty(orderNo, GlobalExceptionCode.ERROR);

        CourseOrder courseOrder = courseOrderService.selectByOrderNo(orderNo);
        if (courseOrder == null){
            return;
        }
        courseOrder.setUpdateTime(new Date());
        courseOrder.setStatusOrder(CourseOrder.CANCEL_PAY_STATUS);
        courseOrderService.updateById(courseOrder);
        // 如果是秒杀订单，还信号量
        Object o = redisTemplate.opsForValue().get(orderNo);
        // 不等于null说明是秒杀订单取消，那么就要退信号量
        if (o != null){
            KillPreOrderParamDto killPreOrderParamDto = JSON.parseObject(JSON.toJSONString(o), KillPreOrderParamDto.class);
            RSemaphore semaphore = redissonClient.getSemaphore(killPreOrderParamDto.getKillActivityId() + ":" + killPreOrderParamDto.getKillCourseId());
            semaphore.trySetPermits(1);
            redisTemplate.delete(orderNo);
        }
    }
}